// FloatingWindowService.java
package com.sion.servicekeep;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.PixelFormat;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.core.app.NotificationCompat;
import androidx.fragment.app.FragmentManager;

public class FloatingWindowService extends Service {

    private static final String TAG = "FloatingWindowService";
    private static final String ACTION_APP_LAUNCHED = "com.sion.servicekeep.ACTION_APP_LAUNCHED"; // 新增广播动作常量
    private WindowManager windowManager;
    private View floatingView;
    private LinearLayout expandedView;
    private ImageView collapsedView;
    private TextView floatingWindowText;
    private int clickCount = 0; // 点击计数器
    private static final int REQUIRED_CLICKS = 5; // 所需点击次数
    private static final long CLICK_INTERVAL = 500; // 点击间隔时间（毫秒）- 增加到500毫秒
    private long lastClickTime = 0; // 上次点击时间
    private static final long CLICK_RESET_TIME = 2000; // 点击重置时间（毫秒）- 2秒内没有点击则重置计数器
    private static final String CHANNEL_ID = "FloatingWindowServiceChannel";
    private static final int NOTIFICATION_ID = 2001;
    private static final long DELAY_TIME = 5000; // 延迟时间 5 秒
    private static final String PASSWORD = "123456"; // 设置密码

    private Handler handler = new Handler();
    private Runnable makeCollapsedViewTransparent = new Runnable() {
        @Override
        public void run() {
            if (collapsedView != null) {
                collapsedView.setBackgroundColor(android.graphics.Color.TRANSPARENT);
            }
        }
    };

    // 重置点击计数器的任务
    private Runnable resetClickCountRunnable = new Runnable() {
        @Override
        public void run() {
            clickCount = 0;
            Log.d(TAG, "Click count reset due to timeout");
        }
    };

    private boolean isDragging = false; // 标记是否正在拖动
    private boolean wasDragging = false; // 标记是否刚刚拖动结束
    private float startX, startY; // 记录触摸开始位置
    private static final float DRAG_THRESHOLD = 20f; // 拖动阈值

    private BroadcastReceiver appLaunchedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (ACTION_APP_LAUNCHED.equals(intent.getAction())) {
                if (collapsedView != null) {
                    // 设置背景颜色为白色
                    collapsedView.setBackgroundColor(Color.WHITE);
                    // 设置折叠视图的 src 属性为 ic_dialog_info
//                    collapsedView.setImageResource(android.R.drawable.ic_dialog_info);
                    // 延迟1秒后设置为透明
                    handler.postDelayed(makeCollapsedViewTransparent, 1000);
                }
            }
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        // 创建通知渠道
        createNotificationChannel();

        // 初始化悬浮窗视图
        floatingView = View.inflate(this, R.layout.floating_window, null);

        // 获取WindowManager服务
        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);

        // 设置悬浮窗类型，根据不同Android版本使用不同的TYPE
        int LAYOUT_FLAG;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_PHONE;
        }

        // 设置悬浮窗布局参数
        final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                LAYOUT_FLAG,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT
        );

        // 设置悬浮窗初始位置
        params.gravity = Gravity.TOP | Gravity.START;
        params.x = 25;
        params.y = 10;

        // 添加悬浮窗到WindowManager
        try {
            windowManager.addView(floatingView, params);
        } catch (Exception e) {
            Log.e(TAG, "Failed to add floating window: " + e.getMessage());
        }

        // 获取展开和折叠视图
        expandedView = floatingView.findViewById(R.id.expanded_container);
        collapsedView = floatingView.findViewById(R.id.collapsed);
        floatingWindowText = floatingView.findViewById(R.id.floating_window_text);

        // 设置展开视图中关闭按钮的点击事件 - 折叠悬浮窗
        floatingView.findViewById(R.id.close_button).setOnClickListener(v ->
                expandedView.setVisibility(View.GONE));

        // 设置展开视图中主按钮的点击事件//之前的展开视图
//        floatingView.findViewById(R.id.main_button).setOnClickListener(v -> {
//            //之前的展开视图
//
//            // 发送广播以关闭目标应用程序
//            Intent intent1 = new Intent("com.sion.servicekeep.ACTION_CLOSE_TARGET_APP");
//            sendBroadcast(intent1);
//            Log.d(TAG, "Sent broadcast to close target app.");
//
//            // 通过公共方法关闭目标应用程序
//            if (getApplicationContext() instanceof MainActivity) {
//                MainActivity mainActivity = (MainActivity) getApplicationContext();
//                // 关闭目标应用程序
//                Log.d("tets", "close");
//                mainActivity.closeTargetApp();
//            }
//
//            // 发送广播以清除选定的目标应用包名
//            Intent intent = new Intent("com.sion.servicekeep.ACTION_CLEAR_PACKAGE_NAME");
//            sendBroadcast(intent);
//            Log.d(TAG, "Sent broadcast to clear selected package name.");
//
//            // 通过公共方法清除选定的目标应用包名
//            if (getApplicationContext() instanceof MainActivity) {
//                MainActivity mainActivity = (MainActivity) getApplicationContext();
//                mainActivity.clearSelectedPackageName();
//                // 停止应用监控
//                if (mainActivity.appLauncher != null) {
//                    mainActivity.appLauncher.stopMonitoring();
//                }
//                //  再次确认标志位已经清除
//                mainActivity.isDaemonCleared = true;
//                super.onDestroy();
//            }
//        });

        // 设置悬浮窗的拖动功能和点击事件

        collapsedView.setOnTouchListener(new View.OnTouchListener() {
            private int initialX;
            private int initialY;
            private float initialTouchX;
            private float initialTouchY;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        // 记录初始位置和触摸点
                        initialX = params.x;
                        initialY = params.y;
                        initialTouchX = event.getRawX();
                        initialTouchY = event.getRawY();
                        startX = event.getRawX();
                        startY = event.getRawY();
                        isDragging = false;
                        wasDragging = false;
                        return true;

                    case MotionEvent.ACTION_MOVE:
                        // 计算移动距离
                        float deltaX = event.getRawX() - startX;
                        float deltaY = event.getRawY() - startY;

                        // 如果移动距离超过阈值，标记为拖动
                        if (Math.abs(deltaX) > DRAG_THRESHOLD || Math.abs(deltaY) > DRAG_THRESHOLD) {
                            if (!isDragging) {
                                isDragging = true;
                                clickCount = 0; // 开始拖动时重置点击计数器
                                handler.removeCallbacks(resetClickCountRunnable);
                                Log.d(TAG, "Started dragging, click count reset");
                            }
                        }

                        if (isDragging) {
                            // 更新悬浮窗位置
                            params.x = initialX + (int) (event.getRawX() - initialTouchX);
                            params.y = initialY + (int) (event.getRawY() - initialTouchY);
                            try {
                                windowManager.updateViewLayout(floatingView, params);
                            } catch (Exception e) {
                                Log.e(TAG, "Failed to update floating window position: " + e.getMessage());
                            }
                        }
                        return true;

                    case MotionEvent.ACTION_UP:
                        if (isDragging) {
                            // 拖动结束
                            isDragging = false;
                            wasDragging = true;
                            Log.d(TAG, "Dragging ended");

                            // 获取屏幕宽度
                            int screenWidth = windowManager.getDefaultDisplay().getWidth();
                            // 判断悬浮窗最终位置相对于屏幕中心点的位置
                            if (params.x < screenWidth / 2) {
                                // 居于屏幕中心点左侧，紧贴左侧屏幕边缘
                                params.x = 0;
                            } else {
                                // 居于屏幕中心点右侧，紧贴屏幕边缘右侧
                                params.x = screenWidth - floatingView.getWidth();
                            }
                            try {
                                windowManager.updateViewLayout(floatingView, params);
                            } catch (Exception e) {
                                Log.e(TAG, "Failed to update floating window position to edge: " + e.getMessage());
                            }
                        } else {
                            // 这是一个点击事件
                            handleClick();
                        }
                        return true;
                }
                return false;
            }
        });

        // 启动延迟任务
        handler.postDelayed(makeCollapsedViewTransparent, DELAY_TIME);

        // 注册广播接收器
        IntentFilter filter = new IntentFilter(ACTION_APP_LAUNCHED);
        registerReceiver(appLaunchedReceiver, filter, Context.RECEIVER_EXPORTED);
    }

    /**
     * 处理点击事件
     */
    private void handleClick() {
        if (wasDragging) {
            wasDragging = false;
            return;
        }

        long currentTime = System.currentTimeMillis();

        // 如果距离上次点击超过重置时间，重置计数器
        if (currentTime - lastClickTime > CLICK_RESET_TIME) {
            clickCount = 0;
            Log.d(TAG, "Click count reset due to timeout");
        }

        // 如果在点击间隔时间内
        if (currentTime - lastClickTime <= CLICK_INTERVAL || clickCount == 0) {
            clickCount++;
            lastClickTime = currentTime;

            Log.d(TAG, "Click count: " + clickCount + "/" + REQUIRED_CLICKS);

            // 移除之前的重置任务
            handler.removeCallbacks(resetClickCountRunnable);

            if (clickCount >= REQUIRED_CLICKS) {
                // 达到所需点击次数，弹出密码输入框
                showPasswordDialog();
                clickCount = 0;
            } else {
                // 设置重置计数器的延迟任务
                handler.postDelayed(resetClickCountRunnable, CLICK_RESET_TIME);
            }
        } else {
            // 点击间隔太短，重置计数器
            clickCount = 1;
            lastClickTime = currentTime;
            Log.d(TAG, "Click too fast, reset count to 1");

            // 设置重置计数器的延迟任务
            handler.removeCallbacks(resetClickCountRunnable);
            handler.postDelayed(resetClickCountRunnable, CLICK_RESET_TIME);
        }
    }

    private void showPasswordDialog() {
        // 创建密码输入框
        final EditText passwordInput = new EditText(this);
        passwordInput.setHint("请输入密码");

        // 使用带有 Theme.AppCompat 主题的上下文创建 AlertDialog.Builder
        AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AppTheme));
        builder.setTitle("认证")
                .setMessage("请输入密码退出守护")
                .setView(passwordInput)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String password = passwordInput.getText().toString();
                        if (password.equals("yuanzhi502")) {
                            ///通过目标应用接收广播来关掉程序
                            Intent intent2 = new Intent("com.richard.yzdigithuman2d.EXIT_APP");
                            sendBroadcast(intent2);
                            Log.d(TAG, "Sent broadcast to close target app.");

                            // 通过公共方法关闭目标应用程序
                            if (getApplicationContext() instanceof MainActivity) {
                                MainActivity mainActivity = (MainActivity) getApplicationContext();
                                // 关闭目标应用程序
                                Log.d("tets", "close");
                                mainActivity.closeTargetApp();
                            }

                            // 发送广播以清除选定的目标应用包名
                            Intent intent = new Intent("com.sion.servicekeep.ACTION_CLEAR_PACKAGE_NAME");
                            sendBroadcast(intent);
                            Log.d(TAG, "Sent broadcast to clear selected package name.");

                            // 通过公共方法清除选定的目标应用包名
                            if (getApplicationContext() instanceof MainActivity) {
                                MainActivity mainActivity = (MainActivity) getApplicationContext();
                                mainActivity.clearSelectedPackageName();
                                // 停止应用监控
                                if (mainActivity.appLauncher != null) {
                                    mainActivity.appLauncher.stopMonitoring();
                                }
                                //  再次确认标志位已经清除
                                mainActivity.isDaemonCleared = true;
                                FloatingWindowService.super.onDestroy();
                            }

                        } else {
                            // 密码错误，提示用户
                            Toast.makeText(FloatingWindowService.this, "密码错误，请重试", Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .setNegativeButton("取消", null);
        // 创建对话框
        final AlertDialog alertDialog = builder.create();
        alertDialog.setCancelable(false); // 禁止点击返回键关闭对话框
        alertDialog.setCanceledOnTouchOutside(false); // 禁止点击对话框外部关闭对话框

        // 设置对话框的窗口类型为 TYPE_APPLICATION_OVERLAY
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
        } else {
            alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_PHONE);
        }

        // 显示对话框
        alertDialog.show();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            String floatingWindowTextStr = intent.getStringExtra("floatingWindowText");
            if (floatingWindowText != null && floatingWindowTextStr != null) {
                floatingWindowText.setText(floatingWindowTextStr);
            }
        }

        // 启动前台服务
        startForeground(NOTIFICATION_ID, createNotification());

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 移除所有延迟任务
        handler.removeCallbacks(makeCollapsedViewTransparent);
        handler.removeCallbacks(resetClickCountRunnable);

        // 服务销毁时移除悬浮窗
        if (floatingView != null) {
            try {
                windowManager.removeView(floatingView);
            } catch (Exception e) {
                Log.e(TAG, "Failed to remove floating window: " + e.getMessage());
            }
        }

        // 注销广播接收器
        unregisterReceiver(appLaunchedReceiver);
    }

    /**
     * 创建通知渠道（Android 8.0+需要）
     */
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "悬浮窗服务",
                    NotificationManager.IMPORTANCE_LOW
            );
            channel.setDescription("用于保持悬浮窗服务运行的通知");
            channel.setShowBadge(false);
            channel.setSound(null, null);
            channel.enableVibration(false);
            channel.setLockscreenVisibility(Notification.VISIBILITY_SECRET);

            NotificationManager manager = getSystemService(NotificationManager.class);
            if (manager != null) {
                manager.createNotificationChannel(channel);
                Log.d(TAG, "Notification channel created");
            }
        }
    }

    /**
     * 创建前台服务通知
     */
    private Notification createNotification() {
        // 点击通知时打开主Activity的Intent
        Intent notificationIntent = new Intent(this, MainActivity.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        notificationIntent.putExtra("startedBy", "FloatingWindowService");

        PendingIntent pendingIntent = PendingIntent.getActivity(
                this,
                0,
                notificationIntent,
                PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
        );

        // 构建通知
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("悬浮窗服务正在运行")
                .setContentText("点击可返回应用")
                .setSmallIcon(android.R.drawable.ic_dialog_info)
                .setContentIntent(pendingIntent)
                .setOngoing(true)  // 设置为持续通知，用户无法滑动删除
                .setPriority(NotificationCompat.PRIORITY_LOW)
                .setShowWhen(false)  // 关闭系统自带的时间显示
                .setAutoCancel(false)
                .setOnlyAlertOnce(true)
                .setCategory(NotificationCompat.CATEGORY_SERVICE);

        return builder.build();
    }
}